import { SysOrder } from "../../GameDef";
import { ECSEntity } from "../../lib/kgame/ecs/ECSEntity";
import { IECSFilter } from "../../lib/kgame/ecs/ECSFilter";
import { ECSSys } from "../../lib/kgame/ecs/ECSSys";
import { MathUtil } from "../../lib/kgame/util/MathUtil";
import { CmpMove } from "../cmp/CmpMove";

/**
 * 移动系统
 */
export class SysMove extends ECSSys {

    get updateOrder(): number {
        return SysOrder.move;
    }

    get ifilter(): IECSFilter {
        return { includeOne: [CmpMove] };
    }

    protected onUpdateEntity(entity: ECSEntity): void {
        const move = entity.getCmp(CmpMove);
        if (move.toDir !== move.moveDir) {
            const diff = MathUtil.radDiff(move.moveDir, move.toDir);
            const add = move.rotSpd * this.scene.dt;
            if (add < Math.abs(diff)) {
                move.moveDir += Math.sign(diff) * add;
            } else {
                move.moveDir = move.toDir;
            }
        }

        //冲刺速度
        const sprintSpdMax = move.moveSpd;
        if (move.isSprint) {
            if (move.sprintSpd < sprintSpdMax) {
                const addSpd = move.moveSpd * this.scene.dt * 2;
                move.sprintSpd = Math.min(sprintSpdMax, move.sprintSpd + addSpd);
            }
        } else if (move.sprintSpd > 0) {
            const reduceSpd = move.moveSpd * this.scene.dt * 4;
            move.sprintSpd = Math.max(0, move.sprintSpd - reduceSpd);
        }

        move.pos.moveRad(move.moveDir, (move.moveSpd + move.sprintSpd) * this.scene.dt);
    }

}